<script>
// 定义一些公共的属性和方法
const bodyHeight = window.innerHeight - 80
const errorMsg = '系统异常'
var switchColor = ['#13ce66', '#dbdbdb'] // switch开关的颜色，第一个为开的颜色，第二个为关的颜色
var EXCEL = {fileFix: '.xlsx',blobType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'}
var WORD = {fileFix: '.docx',blobType: 'application/msword;charset=utf-8'}
var PDF = {fileFix: '.pdf',blobType: 'application/pdf;charset=utf-8'}
var TXT = {fileFix: '.txt',blobType: 'text/plain'}
var setUploadHeaders = {"token": window.sessionStorage.getItem('token')}  //token对象
//日期转String yyyy-MM-dd
function dateToStr (date) {
  if (date == null) {
    return ''
  }
  var d = new Date(date)
  var ar_date = [d.getFullYear(), d.getMonth() + 1, d.getDate()]
  for (var i = 0; i < ar_date.length; i++) ar_date[i] = dFormat(ar_date[i])
  return ar_date.join('-')
  function dFormat (i) {
    return i < 10 ? '0' + i.toString() : i
  }
}

function dateToStrByFormart(date,formart){
  if(date==null){
    return "";
  }
  var d = new Date(date);
  var ar_date1 = [];
  var ar_date = [d.getFullYear(), d.getMonth() + 1];
  if(formart.indexOf("dd")>-1){
    ar_date.push(d.getDate());
  }
  if(formart.indexOf("HH")>-1){
    ar_date1.push(d.getHours());
  }
  if(formart.indexOf("mm")>-1){
    ar_date1.push(d.getMinutes());
  }
  if(formart.indexOf("ss")>-1){
    ar_date1.push(d.getSeconds());
  }
  for (var i = 0; i < ar_date.length; i++) ar_date[i] = dFormat(ar_date[i]);
  for(var i = 0; i < ar_date1.length; i++)ar_date1[i] = dFormat(ar_date1[i]);
  return ar_date.join('-')+(ar_date1.length>0?" "+ar_date1.join(":"):"");
  function dFormat(i) { return i < 10 ? "0" + i.toString() : i; }
}

function getNowDate(formart){
  var d = new Date();
  var ar_date1 = [];
  var ar_date = [d.getFullYear(), d.getMonth() + 1];
  if(formart.indexOf("dd")>-1){
    ar_date.push(d.getDate());
  }
  if(formart.indexOf("HH")>-1){
    ar_date1.push(d.getHours());
  }
  if(formart.indexOf("mm")>-1){
    ar_date1.push(d.getMinutes());
  }
  if(formart.indexOf("ss")>-1){
    ar_date1.push(d.getSeconds());
  }
  for (var i = 0; i < ar_date.length; i++) ar_date[i] = dFormat(ar_date[i]);
  for(var i = 0; i < ar_date1.length; i++)ar_date1[i] = dFormat(ar_date1[i]);
  return ar_date.join('-')+(ar_date1.length>0?" "+ar_date1.join(":"):"");
  function dFormat(i) { return i < 10 ? "0" + i.toString() : i; }
}

//深拷贝数组（支持多维数组）
function deepcopyArray (obj) {
  var out = [],i = 0,len = obj.length
  for (; i < len; i++) {
    if (obj[i] instanceof Array){
      out[i] = deepcopyArray(obj[i])
    }else if(obj[i] instanceof Object){
      for(var item in obj[i]){
        if(obj[i][item] instanceof Array){
          out[i][item] = deepcopyArray(obj[i][item])
        }else{
          if(out[i]==undefined){
            out[i] = {}
          }
          out[i][item] = obj[i][item]
        }
      }
    }else {
      out[i] = obj[i]
    }
  }
  return out
}

//深拷贝数组（支持多维数组）
function deepcopyArrayProperty (obj,copyProperty,notOnlyFlag) {
  var out = [],i = 0,len = obj.length
  for (; i < len; i++) {
    if (obj[i] instanceof Array){
      out[i] = deepcopyArrayProperty(obj[i],copyProperty,notOnlyFlag)
    }else if(obj[i] instanceof Object){
      for(var item in obj[i]){
          if(obj[i][item] instanceof Array){
            if(item in copyProperty){
              out[i][copyProperty[item]] = deepcopyArrayProperty(obj[i][item],copyProperty,notOnlyFlag)
            }else{
              out[i][item] = deepcopyArrayProperty(obj[i][item],copyProperty,notOnlyFlag)
            }
          }else{
            if(out[i]==undefined){
              out[i] = {}
            }
            if(item in copyProperty ){
              out[i][copyProperty[item]] = obj[i][item]
            }else{
                if(notOnlyFlag){
                  out[i][item] = obj[i][item]
                }
            }

          }
      }
    }else {
      out[i] = obj[i]
    }
  }
  return out
}

//生成特定开头的随机字符串
function generate(headStr,length){
  var randStr = "";
  for (var i = 0; i < length; i++) {
    var randItem = Math.floor(Math.random() * 10);
    randStr += randItem;
  }
  return headStr+randStr;
}

/**
 *
 * @param formulaText 要校验的公式
 * @param texts 所有的固定项 以数组的形式传递
 * @returns {boolean} 返回的校验结果 true or false
 */
function checkFormula(formulaText, texts) {
  if (formulaText == null || formulaText == "") {
    return false;
  } else {
    if (formulaText.indexOf("%%") >= 0 || formulaText.indexOf("+%") >= 0
      || formulaText.indexOf("-%") >= 0 || formulaText.indexOf("*%") >= 0
      || formulaText.indexOf("/%") >= 0 || formulaText.indexOf("+") == 0
      || formulaText.indexOf("-") == 0 || formulaText.indexOf("*") == 0
      || formulaText.indexOf("/") == 0 || formulaText.indexOf("%") == 0) {
      return false;
    }
    formulaText = formulaText.replace("%", "/100")
  }
  var hantag = false;//是否包含公式项，默认不包含
  var formulaText1 = formulaText;
  texts.forEach(item => {
    if (formulaText.indexOf(item) >= 0) {
      hantag = true
    }
  })

  texts = texts.sort(function (a, b) {
    return b.length - a.length;
  });
  for (var i = 0; i < texts.length; i++) {
    formulaText1 = formulaText1.replace(new RegExp(texts[i], 'gm'), ",");
    formulaText = formulaText.replace(new RegExp(texts[i], 'gm'), generate("12", 3));
  }
  try {
    eval(formulaText);
    if (hantag) {
      var array = formulaText1.split(",");
      var reg = /^(-?\d+)(\.\d+)?$/
      var reg1 = /^(\d+)(\.\d+)?$/
      for (var i = 0; i < array.length; i++) {
        var tt = array[i];
        if (array[i] == "") {//等于"",表示是公式项
          if (i < array.length - 1 && array[i + 1] == "" && array.length > 2) {//说明两个公式项之间没有运算符
            return false;
          }
          if (i == 0 && i < array.length - 1) {
            //公式项后面不能跟正数
            var tt1 = array[i + 1];
            if (reg1.test(tt1.split("+")[0]) || reg1.test(tt1.split("-")[0]) ||
              reg1.test(tt1.split("*")[0]) || reg1.test(tt1.split("/")[0])) {
              return false;
            }
          }

          if (i == array.length - 1 && array.length != 1) {//公式项前面不能是数字（正数、负数）
            //前面的不能跟数字
            var tt1 = array[i - 1];
            if (reg1.test(tt1.split("+")[tt1.split("+").length - 1]) ||
              reg1.test(tt1.split("-")[tt1.split("-").length - 1]) ||
              reg1.test(tt1.split("*")[tt1.split("*").length - 1]) ||
              reg1.test(tt1.split("/")[tt1.split("/").length - 1])) {
              return false;
            }
          }
        } else {
          var ja = tt.split("+");
          var jian = tt.split("-")
          var chen = tt.split("*")
          var chu = tt.split("/")
          if (i == 0 || i == (array.length - 1)) {//非公式项，并且处于公式的首位、或末尾
            if (i == 0) {//首位
              //首位的最后一个不能是数字
              if (reg.test(ja[ja.length - 1]) || reg.test(jian[jian.length - 1]) || reg.test(chen[chen.length - 1]) || reg.test(chu[chu.length - 1])) {
                return false;
              }
            } else {
              //末尾第一个不能是数字
              if (reg1.test(ja[0]) || reg1.test(jian[0]) || reg1.test(chen[0]) || reg1.test(chu[0])) {
                return false;
              }
            }
          } else {
            /*array中间元素不为空的
             * 那么该元素第一位不能为正数
             * 最后一位不能为数字
             * */
            if (reg1.test(ja[0]) || reg.test(ja[ja.length - 1])
              || reg1.test(jian[0]) || reg.test(jian[jian.length - 1])
              || reg1.test(chen[0]) || reg.test(chen[chen.length - 1])
              || reg1.test(chu[0]) || reg.test(chu[chu.length - 1])
            ) {
              return false;
            }
          }
        }

      }
    }
  } catch (e) {
    return false;
  }
  return true;
}

//数据中添加千位符number为需要转化的数字 decimalNumber为保留的小数位数
function milliFormat(number,decimal) {
  if(number==null || number===""){
    return "";
  }
  if(decimal==null || decimal===""){
    var decimalNumber = 2
  }else{
    var decimalNumber = decimal
  }
  return (Math.round(parseFloat(number)*Math.pow(10,decimalNumber))/Math.pow(10,decimalNumber)).toFixed(decimalNumber)
    .replace(/\d+/, function(s){
      return s.replace(/(\d)(?=(\d{3})+$)/g, '$1,')
    });
}

// 获取select选中的文本
function getSelectLabel(value, options) {

  if((typeof value) == 'object'){
  //  为多选
    var currentLabel = []
    options.forEach(item => {
      value.forEach(it => {
          if (item.value === it) {
            currentLabel.push(item.currentLabel)
          }
      })
    })
  }else{
  //  单选
    var currentLabel = ""
    options.forEach(item => {
      if (item.value === value) {
        currentLabel = item.currentLabel
      }
    })
  }
  return currentLabel
}

// 暴露出这些属性和方法
export default {
  bodyHeight, switchColor, EXCEL, WORD, PDF, TXT, dateToStr,deepcopyArray,dateToStrByFormart,getNowDate,milliFormat, getSelectLabel,checkFormula,generate,deepcopyArrayProperty, errorMsg
}
</script>

<style scoped>

</style>
